package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.mapper.ApBehaviorEntryMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.enums.BehaviorEnum;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * APP行为实体表,一个行为实体可能是用户或者设备，或者其它 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-06
 */
@Service
public class ApBehaviorEntryServiceImpl extends ServiceImpl<ApBehaviorEntryMapper, ApBehaviorEntry> implements IApBehaviorEntryService {

    /**
     * 根据用户ID/设备ID 获取行为实体 如果有直接返回使用，如果没有则新增后返回
     *
     * @param userId
     * @param equipmentId
     * @return
     */
    @Override
    public ApBehaviorEntry getEntry(Integer userId, String equipmentId) {
        //1.优先采用用户ID查询行为实体
        if (ObjectUtils.isNotEmpty(userId)) {
            LambdaQueryWrapper<ApBehaviorEntry> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApBehaviorEntry::getType, BehaviorEnum.BEHAVIOR_ENTRY_TYPE_USER.getVal());
            queryWrapper.eq(ApBehaviorEntry::getEntryId, userId);
            ApBehaviorEntry entry = this.getOne(queryWrapper);
            if (entry != null) {
                return entry;
            } else {
                ApBehaviorEntry insertEntry = new ApBehaviorEntry();
                insertEntry.setEntryId(userId + "");
                insertEntry.setType(BehaviorEnum.BEHAVIOR_ENTRY_TYPE_USER.getVal());
                this.save(insertEntry);
                return insertEntry;
            }
        }
        //2.如果是设备
        if (ObjectUtils.isNotEmpty(equipmentId)) {
            LambdaQueryWrapper<ApBehaviorEntry> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApBehaviorEntry::getType, BehaviorEnum.BEHAVIOR_ENTRY_TYPE_EQUIP.getVal());
            queryWrapper.eq(ApBehaviorEntry::getEntryId, equipmentId);
            ApBehaviorEntry entry = this.getOne(queryWrapper);
            if (entry != null) {
                return entry;
            } else {
                ApBehaviorEntry insertEntry = new ApBehaviorEntry();
                insertEntry.setEntryId(equipmentId + "");
                insertEntry.setType(BehaviorEnum.BEHAVIOR_ENTRY_TYPE_EQUIP.getVal());
                this.save(insertEntry);
                return insertEntry;
            }
        }
        return null;
    }
}
